/******************初始化*****************************************************/
$(function(){
	ParamName={"_userAddLastTabID":"_userAddLastTabID","uptime":"uptime","_defaultPageID":"_defaultPageID","_LocalData":"_LocalData","_boxtabopacity":"_boxtabopacity","_issearchbox":"_issearchbox","_opennewtab":"_opennewtab","_bglocalImg":"_bglocalImg","_bgIndex":"_bgIndex","_searchIndex":"_searchIndex"};
	
	T.init();
	$(window).unbind("resize").bind('resize',function(){
		if (document.body.offsetWidth > 100) {
			T.position();
		}
	});
	$(document).die("selectstart").live("selectstart",function(e){
		if($(e.target).attr('id')!='keyword')
			return false;
	}); 
  
	/////////////////////////////////////////
	$(document).bind("mousedown",function(e){
		if($(e.target).attr("class")=='dimensions'){
			boxs.mousedown(e);
		}
		if($(e.target).attr("class")=='tabli'){
			boxs.tab_mousedown(e);
		}		
	}).bind("mouseup",function(e){
		$(".setuppage").css({'display':'none'});
		$("#ftbox-menu").css({'display':'none'});
		$("#boxstab-menu").css({'display':'none'});
		$("#sotypelist").css({'display':'none'});
		if(boxs._boxMove){
			boxs.mouseup(e);
		}
		if(boxs._tabMove){
			if(!boxs._tabMoveing && e.which==1){
				boxs._tabMove=false;
				boxs.openwindow(e.target);
			}else{
				boxs.tab_mouseup(e);	
			}
		}
	}).bind("mousemove",function(e){
		if(boxs._boxMove){
			boxs.mousemove(e);	
		}
		if(boxs._tabMove){
			boxs.tab_mousemove(e);	
		}
	});
	function wheel(event){
		if (boxs._wheelEvent) {
			boxs.wheel(event);
		}
	}
	if (window.addEventListener) window.addEventListener('DOMMouseScroll', wheel, true);
	window.onmousewheel = wheel;
	
	initChromeI18n();
});
/*****************************************************************************/

/*//存储类*********************************************/
storage = {
	db: localStorage,
	get: function(key, isJson) {
		try {
			return isJson === true ? JSON.parse(this.db.getItem(key)) : this.db.getItem(key);
		} catch(err) {
			return null;
		}
	},
	set: function(key, value, isJson) {
		try {
			if (isJson === true) {
				this.db.setItem(key, JSON.stringify(value));
			} else {
				this.db.setItem(key, value);
			}
		} catch(err) {
		}
	},
	remove: function(key) {
		try {
			this.db.removeItem(key);
		} catch(err) {
		}
	},
	clear: function(keylist) {
		try {
			var self = this;
			if (keylist instanceof Array) {
				$.each(keylist,
				function(i, n) {
					self.db.removeItem(n);
				})
			}
		} catch(err) {
		}
	}
};

//对话框*********************************************/
dialog = {
	html_id:'#adddialog',
	cloud_mask:'#cloud_mask',
	showObj:null,
	param:{},
	init:function(op){
		var top = -parseInt(op.h/2);
		var left = -parseInt(op.w/2);
		var top1 = $(this.html_id).css('top');
		$(this.html_id).css({"width":op.w,"height":op.h,"margin-top": top+'px',"margin-left": left+'px'});
		
		if(op.Close=='hide'){
			$("#adddialog .close").hide();
		}else{
			$("#adddialog .close").show();
		}
		if($(op.obj).length<=0){
			$(".dialogContent").append(op.html);
		}
		this.showObj=op.obj;
		this.showHide(true);
		this.Close();
	},
	Close:function(){
		$(this.html_id+" .close").unbind("click").bind("click",function(){dialog.showHide(false);});
	},
	showHide:function(is){
		var display='none';
		var opacity='0';
		if(is){
			display='block';
			opacity=1;
			boxs._wheelEvent=false;
		}else{
			boxs._wheelEvent=true;
		}
		$(this.showObj).css({"display":display,"opacity":opacity});
		
		$(this.html_id).css({"display":display,"opacity":opacity});
		$(this.cloud_mask).css({"display":display,"opacity":opacity});
	}
	
}
////提示框*********************************************/
Confirm = {
	btn:1,/*1确定和取消  0是确定*/
	tip:chrome.i18n.getMessage('sysHint'),
	text:chrome.i18n.getMessage('sysContent'),
	fun:function(){},
	fun1:function(){},
	init:function(btn,tip,text,fun,fun1){
		this.btn=btn;
		this.tip=tip;
		this.text=text;
		this.fun=fun;
		this.fun1=fun1;
		$(".confirm .top").html(this.tip);
		$(".confirm .span").html(this.text);
		$("#confirm_enter").hide();
		$("#confirm_esc").hide();
		if(this.btn>=0)
			$("#confirm_enter").show();
		if(this.btn>0){
			$("#confirm_esc").show();
		}
	},
	bind:function(){
		$("#confirm_enter").unbind("click").bind("click",function(){
			Confirm.fun();
		});
		$("#confirm_esc").unbind("click").bind("click",function(){
			Confirm.fun1();
		});
	},
	template:function(){
		var h='';
		h+='<div id="confirm" class="confirm onselectstart="return false;" onmousedown="return false;" onmousemove="return false;">';			
		h+='<div class="top"></div>';
		h+='<div class="span"></div>';
		h+='<div class="p">';
		h+='<div class="btn" id="confirm_enter" style="display:none;">'+chrome.i18n.getMessage('ok') +'</div>';
		h+='<div class="btn" id="confirm_esc" style="display:none;">'+chrome.i18n.getMessage('cancel') +'</div>';
		h+='</div>';
		h+='</div>';
		return h;
	}
}
//添加云网址*********************************************/
cloud = {
	classid:-1,
	param:{tabno:-1,index:-1,type:''},
	pagenum:25,
	loadCacheData:{
		1000:{page:1,end:false,data:[]},
		1001:{page:1,end:false,data:[]},
		1002:{page:1,end:false,data:[]},
		1003:{page:1,end:false,data:[]},
		1004:{page:1,end:false,data:[]},
		1005:{page:1,end:false,data:[]},
		1006:{page:1,end:false,data:[]},
		1007:{page:1,end:false,data:[]},
		1008:{page:1,end:false,data:[]},
		1009:{page:1,end:false,data:[]},
		'so':{page:1,end:false,data:[]}
	},
	init:function(){
		this.newSitelogoInit();
		this.bind();
		$("#addinput input[type='text']").val('');
		if(this.classid==-1){
			$("#cloud_menu li[classid='1000']").click();
			this.classid=1000;
		}else if(this.classid=='hand'){
			if(cloud.param.type=='edit'){
				var d=T._tabData[this.param.tabno]['data'][this.param.index];
				$("#addinput input[id='newurl']").val(d.weburl);
				$("#addinput input[id='newtitle']").val(d.title);
				$("#websitelogo").attr({'src': d.img});
			}
			$("#cloud_menu li[classid='hand']").click();
		}
	},
	bind:function(){
		$("#cloud_menu li").unbind("click").bind("click",function(){
			var classid=$(this).attr('classid');
			cloud.classid=classid;
			$(this).parent().find(".selected").removeClass('selected');
			$(this).addClass('selected');
			$('.websiteloading').css("display", "none");
			
			if(classid=='hand'){
				$("#addinput").css({'display':"block"});
				$("#cloud_listbox").css({'display':"none"});
			}else if(parseInt(classid)>0){
				$("#addinput").css({'display':"none"});
				$("#cloud_listbox").css({'display':"block"});
				
				
				$("#cloud_listbox ul[_show='true']").css({'display':"none"}).attr({'_show':'false'});
				$("#cloud_urllist"+classid).css({'display':"block"}).attr({'_show':'true'});
				if(cloud.loadCacheData[classid]['data'].length<=0){
					cloud.loadWebsiteData(classid);
				}
			}
		});
		$("#webkey").unbind("keydown").bind("keydown",function(e){if(e.which==13){cloud.searchKey();}});
		$("#sosearchbtn").unbind("click").bind("click",function(){cloud.searchKey();});
		
		$(".cloud_urllist .imgboxs").die("click").live("click",function(e){
				var el=T._boxlist+" "+T._dimensions+"[_index='"+cloud.param.tabno+"']";
				var obj=$(el).find("li[_index='"+cloud.param.index+"']").get(0);
				var classid=$(this).parent().attr("_classid");
				var index=$(this).parent().attr("_index");
				
				var cloudbox=this;
				dialog.showHide(false);
				setTimeout(function(){
					boxs.editboxs_animate(obj,{cloudbox:cloudbox,type:'data',classid:classid,index:index});
				},300);
		});
		$("#btnaddsite").die("click").live("click",function(e){
			var el=T._boxlist+" "+T._dimensions+"[_index='"+cloud.param.tabno+"']";
			var obj=$(el).find("li[_index='"+cloud.param.index+"']").get(0);

			var webid=cloud.param.webid!='add'?cloud.param.webid:'99999999';
			var url=$.trim($("#addinput input[id='newurl']").val());
			var title=$.trim($("#addinput input[id='newtitle']").val());
			var imgv = $("#websitelogo").attr('src');
			imgv = imgv.replace(_WebUrl,'');
			dialog.showHide(false);
			setTimeout(function(){
				boxs.editboxs_animate(obj,{cloudbox:null,type:'text',id:webid,u:url,t:title,img:imgv});
			},300);
		});
		$(".scroll-list").unbind("scroll").bind("scroll",function(){
				if (this.scrollHeight - this.scrollTop - this.offsetHeight < 10) {
						console.log(this.scrollHeight - this.scrollTop - this.offsetHeight);
					if ($('.websiteloading').css("display") == "none") {
						$('.websiteloading').css("display", "block");
						setTimeout(function() {
							cloud.loadWebsiteData(cloud.classid)
						},
						1000)
					}
				}
		});
	},
	loadWebsiteData:function(classid){
		 var start = (this.loadCacheData[classid]['page'] - 1) * this.pagenum,
		 end = start + this.pagenum;
		 if (this.loadCacheData[classid]['data'].length<=0) {
			 var dataUrl = _WebUrl + 'cloudapp/' + classid + '.json?t='+new Date().getTime();
			$.getJSON(dataUrl,
			function(data) {
				if (data.length > 0) {
					cloud.loadCacheData[classid]['page']=1;
					cloud.loadCacheData[classid]['data']= data;
					cloud.loadWebsite(classid,start, end)
				} else {
					cloud.loadCacheData[classid]['page'] =1;
					cloud.loadCacheData[classid]['data'] = [];
					cloud.loadWebsite(classid,start, end)
				}
			})
		 }else{
			 this.loadWebsite(classid,start, end);
		 }
		 
	},
	loadWebsite:function(classid,start, end){
		if(this.loadCacheData[classid]['data'].length>0){
			var h='';
			var isdata=true;
			for(var i=start;i<end;i++){
				var d=this.loadCacheData[classid]['data'][i];
				if(d=='undefined' || d==null){
					isdata=false;
					break;	
				}
				var is=this.isAddExists(d.id);
				h+='<li title="'+chrome.i18n.getMessage('click2add') +' '+d.t+'" _classid="'+classid+'" _webid="'+d.id+'" _index="'+i+'" _url="'+d.u+'">';
				h+='<div class="imgboxs" style="background-image: url('+ _WebUrl + d.img +');">';
				h+=is?'<div class="add"></div>':'';
				h+='</div>';
				h+='</li>';
			}
			
			if(this.loadCacheData[classid]['page']==1){
				$("#cloud_urllist"+classid).html(h);
			}else{
				$("#cloud_urllist"+classid).append(h);
			}
			this.loadCacheData[classid]['page']++;
			this.loadCacheData[classid]['end']=!isdata;
			if(!isdata){
				//$(".scroll-list").unbind("scroll");	
			}
			
			setTimeout(function() {
			   $('.websiteloading').css("display", "none");
			},500);
		}
		
	},
	isAddExists:function(newid){
		for(var i=0;i<T._tabData.length;i++){
			var d=T._tabData[i]['data'];
			for(var ii=0;ii<d.length;ii++){
				var id=d[ii]['id'];
				if(id=='undefined' ||id<0){
				}else{
					if(newid==id){
						return true;
					}
				}
			}
		}
		return false;
	},
	template:function(){
		h='<div class="addcloud">';
			h+='<p class="recommendedsearch">';
				h+='<input name="webkey" id="webkey" class="webkey"  type="text" placeholder="'+chrome.i18n.getMessage('inputSiteUrl') +'" style=""><input id="sosearchbtn" type="submit" value=" ">';
			h+='</p>';
			h+='<div class="left">';
				h+='<div class="hot">'+chrome.i18n.getMessage('popularSites') +'</div>';
				h+='<ul class="cloud_menu" id="cloud_menu">';
					h+='<li classid="1000"  class="selected"><p>'+chrome.i18n.getMessage('featuredSites') +'</p></li>';
					h+='<li classid="1001"><p>'+chrome.i18n.getMessage('famousSites') +'</p></li>';
					h+='<li classid="1002"><p>'+chrome.i18n.getMessage('coolsSites') +'</p></li>';
					h+='<li classid="1003"><p>'+chrome.i18n.getMessage('gamesSites') +'</p></li>';
					h+='<li classid="1004"><p>'+chrome.i18n.getMessage('videosSites') +'</p></li>';
					h+='<li classid="1005"><p>'+chrome.i18n.getMessage('shoppingSites') +'</p> </li>';
					h+='<li classid="1006"><p>'+chrome.i18n.getMessage('novelSites') +'</p></li>';
					h+='<li classid="1007"><p>'+chrome.i18n.getMessage('newsSites') +'</p></li>';
					h+='<li classid="1008"><p>'+chrome.i18n.getMessage('toolsSites') +'</p></li>';
					h+='<li classid="1009"><p>'+chrome.i18n.getMessage('snsSites') +'</p></li>';
					h+='<li classid="hand"><p >'+chrome.i18n.getMessage('manualAdd') +'</p></li>';
				h+='</ul>';
			h+='</div>';
			h+='<div class="right" id="rightlist">';
					h+='<div id="cloud_listbox" class="cloud_listbox" style="float: left; height: 524px; margin-top: 9px; display: none ">';
						h+='<ul id="cloud_urllist1000" class="cloud_urllist scroll-list" _show="true" style="display:block"><center></center></ul>';
						h+='<ul id="cloud_urllist1001" class="cloud_urllist scroll-list" _show="false" style="display:none"><center></center></ul>';
						h+='<ul id="cloud_urllist1002" class="cloud_urllist scroll-list" _show="false" style="display:none"><center></center></ul>';
						h+='<ul id="cloud_urllist1003" class="cloud_urllist scroll-list" _show="false" style="display:none"><center></center></ul>';
						h+='<ul id="cloud_urllist1004" class="cloud_urllist scroll-list" _show="false" style="display:none"><center></center></ul>';
						h+='<ul id="cloud_urllist1005" class="cloud_urllist scroll-list" _show="false" style="display:none"><center></center></ul>';
						h+='<ul id="cloud_urllist1006" class="cloud_urllist scroll-list" _show="false" style="display:none"><center></center></ul>';
						h+='<ul id="cloud_urllist1007" class="cloud_urllist scroll-list" _show="false" style="display:none"><center></center></ul>';
						h+='<ul id="cloud_urllist1008" class="cloud_urllist scroll-list" _show="false" style="display:none"><center></center></ul>';
						h+='<ul id="cloud_urllist1009" class="cloud_urllist scroll-list" _show="false" style="display:none"><center></center></ul>';
						h+='<ul id="cloud_urllistso" class="cloud_urllist scroll-list" _show="false" style="display:none"><center></center></ul>';
					h+='<div class="websiteloading"><img src="images/loading.gif"></div>';
					h+='</div>';
				
					h+='<div class="addinput" id="addinput" style=" display:none">';
						h+='<div class="newweb">';
						h+='<div class="text fl">';
						h+='<div class="p">';
							h+='<div class="l1">'+chrome.i18n.getMessage('inputURL') +'</div>';
							h+='<div class="l2"> <input type="text" name="newurl" id="newurl"></div>';
						h+='</div>';
						h+='<div class="p">';
							h+='<div class="l1">'+chrome.i18n.getMessage('siteTitle') +'</div>';
							h+='<div class="l2"><input type="text" name="newtitle" id="newtitle"></div>';
						h+='</div>';
						h+='<div class="p">';
							h+='<div class="l1"></div>';
							h+='<div class="l2"><div class="btn add-btn" id="btnaddsite">'+chrome.i18n.getMessage('ok') +'</div></div>';
						h+='</div>';
							
						h+='</div>';
						h+='<div class="logo fr">';
								h+='<div class="newweblogo">';
									h+='<img id="websitelogo" src="' + _WebUrl + 'cloudapp/generalLogo/m/0000.png">';
									h+='<div class="arrow"><span></span></div>';
								h+='</div>';
								h+='<ul class="logolist scroll_logolist">';
								h+='</ul>';
							h+='</div>';
							
							h+='</div>';
				
				
					h+='</div>';
					
			h+='</div>';
			
		h+='</div>';
		
		return h;
	},
	newSitelogoInit:function(){
		var h='';
		for(var i=0;i<=30;i++){
			var file=i>=10?'00':'000';
			h+='<li><img src="' + _WebUrl + 'cloudapp/generalLogo/m/' + file + i +'.png"></li>';
			if(i == "0000"){
				h+='<li><img src="' + _WebUrl + 'cloudapp/generalLogo/m/outLink.png"></li>';
			}
		}
		$("#websitelogo").attr({'src': _WebUrl + "cloudapp/generalLogo/m/0000.png"});
		$(".logolist").html(h);
		
		$(".newweblogo .arrow").die("click").live("click",function(e){
			if($(".logolist").css("display") == "none"){
				$(".logolist").show();
			}else{
				$(".logolist").hide();
			}
		});
		$(".logolist li").die("click").live("click",function(e){
			var img=$(this).find("img").attr('src');
			if(img.indexOf('outLink.png') > -1){
				img = window.prompt(chrome.i18n.getMessage('outerlinkurl'));
			}
			if(img != '' && img != null){
				$("#websitelogo").attr({'src':img});
			}
			$(this).parent().hide();
		});
	},
	searchKey:function(){
		var webkey=$("#webkey").val();
			var classid='so';
			cloud.classid=classid;
			
			$("#addinput").css({'display':"none"});
			$("#cloud_listbox").css({'display':"block"});
			$("#cloud_listbox ul[_show='true']").css({'display':"none"}).attr({'_show':'false'});
			$("#cloud_urllist"+classid).css({'display':"block"}).attr({'_show':'true'});
			
			cloud.loadCacheData[classid]['page'] =1;	
			cloud.loadCacheData[classid]['data'] = [];
			if(webkey==''){
				$("#cloud_urllist"+classid).html('<BR><BR><BR><BR><BR><center style="font-size:18px;">'+chrome.i18n.getMessage('inputSiteUrl') +'</center>');
			}else{
				if(_browser.language == "zh_CN"){
					return false;
				}
				$("#cloud_urllist"+classid).html('');
				var dataUrl = _WebUrl + 'server/search.php?keyword='+encodeURIComponent(webkey)+'&t='+new Date().getTime();
				$.getJSON(dataUrl,
					function(data) {
						if (data.length > 0) {
							cloud.loadCacheData[classid]['page'] =1;
							cloud.loadCacheData[classid]['data']= data;
							cloud.loadWebsite(classid,0, cloud.pagenum);
						} else {
							cloud.loadCacheData[classid]['page'] =1;
							cloud.loadCacheData[classid]['data'] = [];
							$("#cloud_urllist"+classid).html('<BR><BR><BR><BR><BR><center style="font-size:18px;">'+chrome.i18n.getMessage('withoutURData') +'</center>');
						}
						
					}
				);
			}
	}
}
/*//框子列表*********************************************/
boxs = {
	boxArr:new Array(),
	_sourceX:0,
	_offsetx:0,
	_mouseoffsetx:110,
	_object_move:null,
	_wheelEvent:true,
	_boxMove:false,
	/**********************/
	_liobj_Move:null,
	_tabMove:false,
	lioffset:{x:0,y:0},
	_tabX:0,
	_tabY:0,
	_item:-1,
	_itemMove:-1,
	_itemOut:-1,
	_arrMove:new Array(),
	_tabMoveing:false,
	_tabMoveNumX:0,
	_tabMoveNumY:0,
	init:function(){
		var arr=new Array();
		var W=351,H=216;
		var i=j=0;
		for(var ii=0;ii<12;ii++){
			var arr1=new Array();
			arr1['left']=i*W;
			arr1['top']=j*H;
			arr1['width']=i*W+W;
			arr1['height']=j*H+H;
			arr.push(arr1);	
			
			if(i<3){
				i++;
			}else{
				j++;
				i=0;	
			}
		}
		this.boxArr=arr;
		this.loadboxlist();	
		$(".boxPageBtn").unbind("click").bind("click",function(e){boxs.pageNextPrv($(this).attr('_data'));});
		$(".tagbox li[webid!='add']").die("mouseover").live("mouseover",function(e){
			$(this).find(".infotext").stop(true,false).animate({
						'margin-top':170
			},150);
		}).die("mouseout").live("mouseout",function(e){
			$(this).find(".infotext").stop(true,false).animate({
				'margin-top':216
			},150);
		});
		
		$(".tagbox li").die("mouseover").live("mouseover",function(e){
			$(this).css({'opacity':1});
		}).die("mouseout").live("mouseout",function(e){
			$(this).css({'opacity':(1-T._boxtabopacity)});
		});
		
		$(".tagbox li").die("click").live("click",function(e){
			var webid=$(this).attr('webid');
			if(!boxs._tabMoveing && webid=='add'){
				boxs.addcloudWeb(e);
			}
		});
	},
	loaddata:function(){
		var pageid=T.getPageid();
		var d=T._tabData;
		
		var h='';
		var curpage=-1;///-1 0 1
		for(var i=0;i<d.length;i++){
			if(pageid==-1 && i==0){
				curpage=0;
				pageid=d[i]['id'];
				T.setPageid(pageid);
			}else{
				if(parseInt(pageid)==parseInt(d[i]['id'])){
					curpage=0;
				}else{
					if(curpage==0){
						curpage=1;
					}
				}
			}
			
			h+=this.template(d[i]['data'],d[i]['id'],curpage,i);
		}
		return h;
	},
	loadboxlist:function(){
		$(T._boxlist).html(boxs.loaddata());
		this._object_move=$(T._boxlist).find("div[_type='center']");
		if(this._object_move.length<=0){
			T.setPageid(-1);
			$(T._boxlist).html(boxs.loaddata());
			this._object_move=$(T._boxlist).find("div[_type='center']");
		}
	},
	template:function(data,pageid,curpage,tabno){
		var h = '';
		h += '<div class="dimensions" pageid="'+pageid+'" _index="'+tabno+'" style="left: '+curpage+'px; opacity: '+(curpage==0?'1':'0')+'; height: 0; width: 0px; " _type="'+(curpage==0?'center':'')+'">';
		h += '<div class="space" style="-webkit-transform-origin: 50% 50%;-moz-transform-origin: 50% 50%;" onselectstart="return false;">';
		h += '<ul id="tagbox'+pageid+'" class="tagbox" onselectstart="return false;">';
		for(var i=0; i<data.length;i++){
			var arr={'left':this.boxArr[i]['left'],'top':this.boxArr[i]['top'],'width':this.boxArr[i]['width'],'height':this.boxArr[i]['height']};
			if(data[i]['id']!='undefined' && data[i]['id']>0){
				var bgimg = "";
				var cacheurl = "";
				if(curpage == 0){//为了延迟显示
					bgimg += "background-image: url(" + data[i]['img'] + ");background-position:center center;background-size:auto auto;background-color:#FFF;";
					cacheurl='';
				}else{
					bgimg += "background-image: url(images/loadboximg.gif);background-position:center center;background-size:auto auto;background-color:#FFF;";
					cacheurl='_cacheurl="' + data[i]['img'] + '"';
				}
				h += '<li  pageid="'+pageid+'" _tabno="'+tabno+'" webid="'+data[i]['id']+'" _index="'+i+'" _url="'+data[i]['weburl']+'" style="left: '+arr.left+'px; top: '+arr.top+'px; width: '+(arr.width-arr.left)+'px; height: '+(arr.height-arr.top)+'px; opacity: '+(1-T._boxtabopacity)+'; '+bgimg+'" '+cacheurl+'  class="tabli"  onselectstart="return false;">';
				h += '<div class="infotext"  onselectstart="return false;" onmousedown="return false;" onmousemove="return false;"  style="width: '+(arr.width-arr.left)+'px; margin-top: 216px; opacity: 1; display: block; "><h2>'+data[i]['title']+'</h2></div>';
				if(typeof data[i]['html'] != 'undefined' && data[i]['html'] != ""){
					h += '<div style="display:none;">' + data[i]['html'] + '</div>';
				}
				h += '</li>';
			}else{
				h += '<li " pageid="'+pageid+'" _tabno="'+tabno+'" webid="add" _index="'+i+'" style="left: '+arr.left+'px; top: '+arr.top+'px; width: '+(arr.width-arr.left)+'px; height: '+(arr.height-arr.top)+'px; opacity: '+(1-T._boxtabopacity)+'; background-image: url(images/add1.png); background-size: 100%; margin-left: 0px; margin-top: 0px; background-position: initial initial; background-repeat: no-repeat no-repeat; "  class="tablic"></li>';
			}
		}
		h += '</ul></div></div>';
	
	return h;
	},
	tempEDhtml:function(img,arr){
		return '<div class="newimg" style=" left: 0px; top: -216px; width: '+(arr.width-arr.left)+'px; height: '+(arr.height-arr.top)+'px; z-index:20;opacity: 1; background-image: url('+img+'); cursor: pointer; margin-left: 0px; margin-top: 0px; background-position:center center;background-size:auto auto;background-color:#FFF; background-repeat: no-repeat no-repeat;"></div>';
	},
	delboxs_animate:function(obj){
		var i=$(obj).attr('_index');
		var arr={'left':this.boxArr[i]['left'],'top':this.boxArr[i]['top'],'width':this.boxArr[i]['width'],'height':this.boxArr[i]['height']};
			
			var webid=	$(obj).attr('webid');
			$('.addcloud .cloud_listbox li').each(function(index, el) {
				var _webid=$(el).attr('_webid');
				
				if(webid==_webid){console.log(chrome.i18n.getMessage('deleteSuccessful'));
					$(this).find(".imgboxs").html('');
				}
			});	

			var img='images/add1.png';
			var html=this.tempEDhtml(img,arr);
			$(obj).append(html);
			var newimg=$(obj).find(".newimg");
			newimg.stop(true,false).animate({'top':0},600,function(){
				$(obj).css({'background-image':'url('+img+')'});
				newimg.remove();
			});
			$(obj).removeAttr("_url");
			$(obj).attr({"webid":'add'});
			$(obj).attr({"class":'tablic'});
			$(obj).find(".infotext").remove();
	},
	editboxs_animate:function(obj,op){//op.t=data或text
		var i=$(obj).attr('_index');
		var tabno=$(obj).attr('_tabno');
		var arr={'left':this.boxArr[i]['left'],'top':this.boxArr[i]['top'],'width':this.boxArr[i]['width'],'height':this.boxArr[i]['height']};
		var img='';
		var d={};
		if(op.type=='data'){
			d=cloud.loadCacheData[op.classid]['data'][op.index];
			$(op.cloudbox).html('<div class="add"></div>');
		}else if(op.type=='text'){
			d=op;
		}
		var img = _WebUrl + d.img;
		if(d.img.indexOf('http://') > -1){
			img = d.img;
		}
		var html=this.tempEDhtml(img,arr);
		$(obj).append(html);
		var newimg=$(obj).find(".newimg");
		newimg.stop(true,false).animate({'top':0},800,function(){
			$(obj).css({'background-image':'url('+img+')'});
			newimg.remove();
			$(obj).html('<div class="infotext"  style="width: '+(arr.width-arr.left)+'px; margin-top: 216px; opacity: 1; display: block; "><h2>'+d.t+'</h2></div>');
		});
		if(!isHttp(d.u)){d.u="http://"+d.u;}
		$(obj).attr({"webid":d.id});
		$(obj).attr({"_url":d.u});
		$(obj).attr({"class":"tabli"});
		var data=T._tabData;
		data[tabno]['data'][i]={id:d.id,title:d.t,weburl:d.u,img:img};
		T.setTabDataJson(data);
			
			
	},
	openwindow:function(obj){
		var webid=$(obj).attr("webid");
		var _url=$(obj).attr("_url");
		if(!isHttp(_url)){_url="http://"+_url;}
		var goto = _url;
		
		if(config.clickcount){
			goto = _WebUrl + "server/click.php?webid="+webid+"&url="+encodeURIComponent(_url);
		}

		openTab(T._opennewtab,goto,tabID);
	},
	editwindow:function(obj){
		cloud.classid='hand';
		var tabno=$(obj).attr("_tabno");
		var index=$(obj).attr("_index");
		var webid=$(obj).attr('webid');
		cloud.param={tabno:tabno,index:index,webid:webid,type:'edit'};
		dialog.init({w:750,h:500,obj:'.addcloud',html:cloud.template()});
		cloud.init();
	},
	delwindow:function(obj){
		var tabno=$(obj).attr("_tabno");
		var index=$(obj).attr("_index");
		var d=T._tabData;
		d[tabno]['data'][index]=[];
		T.setTabDataJson(d);
		this.delboxs_animate(obj);
	},
	addcloudWeb:function(e){
		var tabno=$(e.target).attr("_tabno");
		var index=$(e.target).attr("_index");
		var webid=$(e.target).attr('webid');
		cloud.param={tabno:tabno,index:index,webid:webid,type:'add'};
		dialog.init({w:750,h:500,obj:'.addcloud',html:cloud.template()});
		cloud.init();
	},
	mousedown:function(e){
		this._object_move=$(e.target);
		
		this._wheelEvent=true;
		this._boxMove=true;
		this._offsetx=parseInt(e.pageX)-parseInt(this._object_move.offset().left);
		this._sourceX=e.pageX;
	},
	mouseup:function(e){
		this._boxMove=false;
		var x=parseInt(this._object_move.css("left"));
		var isSlide=(x>this._mouseoffsetx || x<-this._mouseoffsetx)?true:false;
		var nw=this._object_move.width();
		
		var obj_prv=this._object_move.prev();
		var obj_next=this._object_move.next();
		if(x!=0 && !isSlide){//返回
			this.pageslide(this._object_move,0,1);
			if(x>0){
				this.pageslide(obj_prv,-nw,0);
			}else if(x<0){
				this.pageslide(obj_next,nw,0);
			}
		}else{//要翻
			if(isSlide && x>this._mouseoffsetx && obj_prv.length){
				this.pageslide(this._object_move,nw,0);
				this.pageslide(obj_prv,0,1);
				obj_prv.attr({'_type':'center'});
				this._object_move.attr({'_type':''});
				this._object_move=obj_prv;
				ftbox.setftboxcurrent();
			}else if(isSlide && x<-this._mouseoffsetx && obj_next.length){
				this.pageslide(this._object_move,-nw,0);
				this.pageslide(obj_next,0,1);
				obj_next.attr({'_type':'center'});
				this._object_move.attr({'_type':''});
				this._object_move=obj_next;
				ftbox.setftboxcurrent();
			}else{
				this.pageslide(this._object_move,0,1);
			}
		}
	},
	mousemove:function(e){
		var x=parseInt(e.pageX)-this._offsetx;
		var opac=this.getopacity(x);
		
		this._object_move.css({'left':x+"px",'opacity':opac.opacity1});
		
		var nw=this._object_move.width();
		var obj_next=this._object_move.next();
		var obj_prv=this._object_move.prev();
		
		if(this._sourceX>e.pageX){
			if(obj_next.length){
				obj_next.css({'left':x+nw,'opacity':opac.opacity});
			}
		}else{
			if(obj_prv.length){
				obj_prv.css({'left':x-nw,'opacity':opac.opacity});
			}
		}
		
	},
	pageslide:function(object,x,opacity){
	  object.stop(true,false).animate({'left':x,"opacity":opacity},400);
	},
	wheel:function (event){
		this._wheelEvent = false;
		var delta = 0;
		
		if (!event) event = window.event;
		if (event.wheelDelta) {
			delta = delta + event.wheelDelta
		} else if (event.detail) {
			delta = delta + ( - event.detail * 40)
		}
		if(delta>0){
			x=this._mouseoffsetx;
		}else{
			x=-this._mouseoffsetx;	
		}
		this.pageNextPrv(x);
		
		if (event.preventDefault) event.preventDefault();
		event.returnValue = true;
		setTimeout(function() {
			boxs._wheelEvent = true
		},600);
	},
	pageNextPrv:function(x){
		var nw=this._object_move.width();
		var obj_prv=this._object_move.prev();
		var obj_next=this._object_move.next();
		
		//要翻
		if(x>0 && obj_prv.length){
			this.pageslide(this._object_move,nw,0);
			this.pageslide(obj_prv,0,1);
			obj_prv.attr({'_type':'center'});
			this._object_move.attr({'_type':''});
			this._object_move=obj_prv;
			ftbox.setftboxcurrent();
			
		}else if(x<0 && obj_next.length){
			this.pageslide(this._object_move,-nw,0);
			this.pageslide(obj_next,0,1);
			obj_next.attr({'_type':'center'});
			this._object_move.attr({'_type':''});
			this._object_move=obj_next;
			ftbox.setftboxcurrent();
		}else{
			if(x>0){
				this._object_move.stop(true,false).animate({'left':200},400,function(){
				 boxs.pageslide(boxs._object_move,0,1);
				 });
			}else{
			 this._object_move.stop(true,false).animate({'left':-200},400,function(){
				 boxs.pageslide(boxs._object_move,0,1);
				 });
			}
		}
	},
	loadboxImg:function(obj){
		obj.find("li[webid!='add']").each(function(index, el) {
			var _imgurl=$(el).attr("_cacheurl");
			if(_imgurl!='' && _imgurl!=undefined){
				$(el).css({"background-image":"url("+_imgurl+")"});
				$(el).removeAttr("_cacheurl");
			}
		});
	},
	gettabpos:function(e){
		var index=-1;
		var posX=(parseInt(e.pageX)-$(e.target).parent().offset().left)/T._Boxs_scale;
		var posY=(parseInt(e.pageY)-$(e.target).parent().offset().top)/T._Boxs_scale;
			var arr=boxs.boxArr;
			var count=arr.length;
			for(var i=0;i<count;i++){
				if(posX>arr[i]['left'] && posY>arr[i]['top'] &&
					posX<arr[i]['width'] && posY<arr[i]['height']){
					index=i;
					break;	
				}
			}
		return index;
	},
	tab_mousedown:function(e){
		var index=this.gettabpos(e);//拖动元素
		this._liobj_Move=e.target;
		this._tabX=parseInt(e.pageX)/T._Boxs_scale-parseInt($(e.target).css("left"));
		this._tabY=parseInt(e.pageY)/T._Boxs_scale-parseInt($(e.target).css("top"));
		this._item=index;
		this._tabMove=true;
		this._tabMoveNumX=e.pageX;
		this._tabMoveNumY=e.pageY;
	},
	tab_mouseup:function(e){

		var obj1=null;
		var obj=this._liobj_Move;
		var index=this._item;
		var x1=0;
		var y1=0;
		var indexOut=0;
		if(this._itemOut!=-1){//在有效框中松开
			indexOut=this._itemOut;
			this._itemOut=-1;
			obj1=this.getTabliobj(indexOut);
			x1=boxs.boxArr[indexOut]['left'];
			y1=boxs.boxArr[indexOut]['top'];
			
		}
		
		var x=boxs.boxArr[index]['left'];
		var y=boxs.boxArr[index]['top'];
		
		if(obj1!=null && indexOut!=-1){
			$(obj).attr({"_index":indexOut});
			$(obj).removeClass("move");
			$(obj).stop(true,true).animate({
							'left':x1+'px',
							'top':y1+'px',
							"z-index":'0'
						},500);
			$(obj1).attr({"_index":index});
			$(obj1).removeClass("move");
			$(obj1).stop(true,true).animate({
							'left':x+'px',
							'top':y+'px',
							"z-index":'0'
						},500,function(){boxs._tabMoveing=false;});
			this.adjustTabliPos(index,indexOut);
		}else{
		$(obj).removeClass("move");
		$(obj).stop(true,true).animate({
							'left':x+'px',
							'top':y+'px',
							"z-index":'0'
						},500,function(){boxs._tabMoveing=false;});
		}
		this._tabMove=false;
	},
	tab_mousemove:function(e){
		//console.log('正在移动');
		if(this._tabMove && ((e.pageX/T._Boxs_scale)!=((this._tabMoveNumX)/T._Boxs_scale) || (e.pageY/T._Boxs_scale)!=((this._tabMoveNumY)/T._Boxs_scale))){
		this._tabMoveing=true;
		var x=parseInt(e.pageX)/T._Boxs_scale-this._tabX;
		var y=parseInt(e.pageY)/T._Boxs_scale-this._tabY;
		$(this._liobj_Move).css({top:y,left:x,"z-index":'15'});
		///判断是否在一个元素内
		var posX=(parseInt(e.pageX)-$(e.target).parent().offset().left)/T._Boxs_scale;
		var posY=(parseInt(e.pageY)-$(e.target).parent().offset().top)/T._Boxs_scale;
		
		var arr=boxs.boxArr;
		var count=arr.length;
		
		var index=this.gettabpos(e);//拖动元素
		if(index>=0 && index!=this._item){
			if(this._itemOut!=index && this._itemOut!=-1){
				this.tab_boxmovepos(e,this._itemOut,-1);
			}
			this._itemOut=index;
			
			if(this._itemMove!=index && this._itemOut!=-1){
				this.tab_boxmovepos(e,index,1);
			}
			this._itemMove=index;
		}else if(this._itemOut!=-1){
			this.tab_boxmovepos(e,this._itemOut,-1);
			this._itemOut=-1;
		}else if(index<0){
			this._itemOut=this._itemMove=-1;
		}
		if(index==this._item){
			this._itemMove=index;
		}
		}


	},
	tab_boxmovepos:function(e,index,t){//对象移动经过时，触发位移动画
		this._arrMove.push(index);
		//当前对象的中心坐标
		var center_left=boxs.boxArr[index]['left'];
		var centet_top=boxs.boxArr[index]['top'];
		
		var mousedown_center_left=boxs.boxArr[this._item]['left'];
		var mousedown_center_top=boxs.boxArr[this._item]['top'];
		
		//设置位偏移量
		var x = (mousedown_center_left>center_left)?20:((mousedown_center_left==center_left)?0:-20);
		var y = (mousedown_center_top>centet_top)?20:((mousedown_center_top==centet_top)?0:-20);
		var zindex=0;
		var self=this.getTabliobj(index);
		if(t>0){
			x=center_left+x;
			y=centet_top+y;
			zindex=12;
			self.addClass("move");
		}else{
			x=center_left;
			y=centet_top;
			zindex=0;
			self.removeClass("move");
		}
		
		self.css({'z-index':zindex});
		
		self.stop(true,false).animate({
			'left':x+'px',
			'top':y+'px'
		},200,function(){});
	},
	getTabliobj:function(index){
		return $(T._boxlist+" "+T._dimensions+"[_type='center']").find("li[_index='"+index+"']");
		//return $("#boxlist .dimensions[_type='center']").find("li[_index='"+index+"']");
	},
	adjustTabliPos:function(sid,eid){
		var self=$(T._boxlist+" "+T._dimensions+"[_type='center']");
		var d_index=self.attr("_index");//数据索引
		var d=new Array();
		var dtimp=new Array();
		d=T._tabData;
		dtimp=d[d_index]['data'][sid];
		d[d_index]['data'][sid]=d[d_index]['data'][eid];
		d[d_index]['data'][eid]=dtimp;
		T.setTabDataJson(d);
		
	},
  getopacity:function(left){
	  var c=Math.abs(left)/T._windowWidth;
	  c=c>0?c:0;
	  c=c>=1?1:c;
	  var opac=c;
	  
	  var c1=(T._windowWidth-Math.abs(left))/T._windowWidth;
	  c1=c1>0?c1:0;
	  c1=c>=1?1:c1;
	  var opac1=c1;
	  
	return {'opacity':opac,'opacity1':opac1};
  }
  
}
////底部标签*********************************************/
ftbox = {
	_total:0,
	_width:0,
	_W:90,
	_indexID:0,
	_indexID1:0,
	_otherMove:false,
	init:function(){
		this.drag();
		this.loadftbox();
		this.onclick();
		this.addtag();
	},
	loadftbox:function(){
		$(T._ftbox).html(ftbox.loaddata());
		var object=$(T._ftbox).find("li[class='st st2']");
		if(object.length<=0){
			T.setPageid(-1);
			$(T._ftbox).html(ftbox.loaddata());
		}
	},
	loaddata:function(){
		var pageid=T.getPageid();
		var d=T._tabData;
		var str='';
		this._total=0;
		for(i=0;i<d.length;i++){
			this._total++;
			if(pageid==-1 && i==0){
				curpage='st2';
				T.setPageid(d[i]['id']);
				this._indexID=0;
			}else{
				curpage=parseInt(pageid)==parseInt(d[i]['id'])?'st2':'st1';
				if(curpage=='st2'){this._indexID=i;}
			}
			str+='<li class="st '+curpage+'"  pageid="'+d[i]['id']+'" _name="'+d[i]['name']+'" _index="'+i+'" style="width:90px;">'+d[i]['name']+'<div class="ftbox_a"></div><div class="menu-tip"></div></li>';
		}
		this._width=(parseInt(this._total)+1)*parseInt(this._W);
		str += '<span class="st st3" _type="add" style="width: 90px; ">+</span>';
		return str;
	},
	adjustPagePos:function(element){
		var d=new Array();
		this._total=0;
		$(element).find('li').each(function(index, element) {
			this._total++;
			var _index=$(element).attr('_index');
			d[index]=T._tabData[_index];
		});
		this._width=(parseInt(this._total)+2)*parseInt(this._W);
		T.setTabDataJson(d);
		T.refreshHtml();
	},
	setftboxcurrent:function(){
		boxs.loadboxImg(boxs._object_move);///切换显示图片
		var pageid=boxs._object_move.attr("pageid");
		var _index=boxs._object_move.attr("_index");
		this._indexID=_index;
		T.setPageid(pageid);
		
		var object=$(T._ftbox).find(".st2");
		object.removeClass("st2");
		object.addClass("st1");
		
		$(T._ftbox+" li[_index='"+_index+"']").removeClass("st1");
		$(T._ftbox+" li[_index='"+_index+"']").addClass("st2");
	},
	drag:function(){
		$(T._ftbox).sortable({
			addClasses:false,
			distance:5,
			tolerance: 'pointer',
			revert:true,
			items:'li',
			zIndex:2,
			start: function(event,ui) {
				var self=$(this);
			},
			stop:function(event,ui){
				ftbox.adjustPagePos(this);
			}
		});	
	},
	onclick:function(){
		$(T._ftbox + " li").die("click").live("click",function(e){
			var object=$(this).parent().find(".st2");
			object.removeClass("st2");
			object.addClass("st1");
			
			$(this).removeClass("st1");
			$(this).addClass("st2");
			ftbox._indexID1 = $(this).attr("_index");
			
			var pageid=$(this).attr("pageid");
			T.setPageid(pageid);
	
			if(ftbox._indexID1 < ftbox._indexID){//向左
				var ii=ftbox._indexID-ftbox._indexID1;
				for(var i=0;i<ii;i++){
					boxs.pageNextPrv(1);
				}
			}else if(ftbox._indexID1 > ftbox._indexID){//向右
				var ii=ftbox._indexID1-ftbox._indexID;
				for(var i=0;i<ii;i++){
					boxs.pageNextPrv(-1);
				}
			}
			
			ftbox._indexID = ftbox._indexID1;
		});	
	},
	addtag:function(){
		$(T._ftbox+" span").die("click").live("click",function(e){
			if(ftbox._total >= 10){
				dialog.init({Close:'hide',w:330,h:160,obj:'#confirm',html:Confirm.template()});
				Confirm.init(0,chrome.i18n.getMessage('sysHint'),chrome.i18n.getMessage('imgSizeLimit'),function(){
					dialog.showHide(false);
				},function(){});
				Confirm.bind();
			}else{
				var tid = ftbox.getuserTabID();
				tid++;
				d=T._tabData;
				d.push(JSON.parse('{"id":'+tid+',"name":"'+chrome.i18n.getMessage('myfavorite')+'","data":[[],[],[],[],[],[],[],[],[],[],[],[]]}'));
				T.setTabDataJson(d);
				ftbox.setuserTabID(tid);
				T.setPageid(tid);
				///重新加载
				T.refreshHtml();
			}
		})
	},
	getuserTabID:function(){
		var d = storage.get(ParamName._userAddLastTabID,false);
		if(d == null){
			d = 10000;
			this.setuserTabID(d);
		}
		return d;
	},
	setuserTabID:function(d){
		storage.set(ParamName._userAddLastTabID,d,false);
	},
};

////菜单*********************************************/
menu = {
	init:function(){
		$(T._ftbox+" li").die('contextmenu').live('contextmenu',function(e){ 
			menu.ftshowmenu(e,$(this));
			return false;
		}); 
		$(T._boxlist+" "+T._dimensions+"[_type='center'] .tagbox li[webid!='add']").die("contextmenu").live('contextmenu',function(e){
			menu.boxtagshowmenu(e,$(this));
			return false;
		});
		this.ftboxmenu();
	},
	ftshowmenu:function(e,obj){
		var self=$("#ftbox-menu");
		self.css({'opacity':0,left:e.pageX+5,top:e.pageY-65,'display':'block'});
		self.stop(true,false).animate({'opacity':1},350);
		
		self.find('button').unbind("mouseup").bind("mouseup",function(){
			var data=$(this).attr('data-action');			
			if(data=='deltype'){//删除分类
				dialog.init({Close:'hide',w:330,h:160,obj:'#confirm',html:Confirm.template()});
				Confirm.init(1,chrome.i18n.getMessage('sysHint'),chrome.i18n.getMessage('deleteConfirm'),function(){
					dialog.showHide(false);
					menu.delftboxtab(obj);
				},function(){dialog.showHide(false);});
				Confirm.bind();
				
			}else if(data=='rename'){//重命名
					var text=obj.text();
					obj.html('<input type=text><div class="ftbox_a"></div><div class="menu-tip"></div>');
					obj.find("input").val(text);
					obj.find("input").focus();
					obj.find('input').unbind('click').bind('click',function(){
						return false;	
					}).unbind('focusout').bind('focusout',function(){
						menu.saveftboxtext(obj);
					}).unbind("keyup").bind('keyup',function(e){
						if(e.keyCode==13){
							obj.find("input").blur();
						}
					});
			}
			self.css({'display':'none'});
			return false;
		});
	},
	boxtagshowmenu:function(e,obj){
		var self=$("#boxstab-menu");
		self.css({'opacity':0,left:e.pageX+5,top:e.pageY,'display':'block'});
		self.stop(true,false).animate({'opacity':1},350);
		
		self.find('button').unbind("mouseup").bind("mouseup",function(){
			var data=$(this).attr('data-action');
			if(data=='delete'){	///删除tag
				boxs.delwindow(obj);
			}else if(data=='open'){//打开网址
				boxs.openwindow(obj);
			}else if(data=='edit'){//编辑
				boxs.editwindow(obj);
			}
			self.css({'display':'none'});
			return false;
		});
	},
	ftboxmenu:function(){
		$(T._ftbox+" .menu-tip").unbind("click").bind("click",function(e){
			menu.ftshowmenu(e,$(this).parent());
			
		})
	},
	saveftboxtext:function(obj){
		var pageid=obj.attr('pageid');
		var _index=obj.attr('_index');
		
		var text=obj.text();
		var temp=T.truncate(obj.find("input").val(),10);
		if(temp=='')temp=text;
		obj.html(temp+'<div class="ftbox_a"></div><div class="menu-tip"></div>');
		obj.attr({'_name':temp});
		var d=new Array;
		d=T._tabData;
		d[_index]['name']=temp;
		T.setTabDataJson(d);
	},
	delftboxtab:function(obj){
		if(ftbox._total<=1){//最少保留一个标签
			return ;	
		}
		var ft_pageid=obj.attr('pageid');
		var _index=obj.attr('_index');
		var d=new Array;
		d=T._tabData;
		d.remove(_index);
		T.setTabDataJson(d);
		//
		var pageid=T.getPageid();
		if(ft_pageid==pageid){
			var obj_next=obj.next();
			var obj_prv=obj.prev();
			if(obj_prv.length>0){
				obj_prv.click();
			}else if(obj_next.length>0){
				obj_next.click();
			}else{
				T.setPageid(-1);
			}
		}
		var parent_obj=obj.parent();
		$(obj).remove();
		ftbox._total=0;
		parent_obj.find("li").each(function(index, el) {
			ftbox._total++;
			$(el).attr({'_index':index});
		});
		ftbox._width=ftbox._total*ftbox._W+ftbox._W;
		
		$(T._boxlist+" "+T._dimensions+"[_index='"+_index+"']").remove();
		$(T._boxlist+" "+T._dimensions).each(function(index, el) {
			 $(el).attr({'_index':index});
		});
		
		T.position();
		
	}
	
}
///搜索*********************************************/
so = {
	d:d,
	init:function(){		
		this.isVisible(T._issearchbox,'init');
		this.loadData(T._searchIndex);
		this.setSoType(T._searchIndex);
		
		this.autocomplete();
		if(this.d.length <= 1){
			$("#searchbox .arrowv").hide();
			$(".sotype").css("width","90px");
		}
		$("#searchbox .arrowv").unbind("click").bind("click",function(){
			var isshow=$("#sotypelist").is(":visible");
			if(!isshow){
				$("#sotypelist").show();
			}else{
				$("#sotypelist").hide();
			}
		});
		$(".sotype").find("a").unbind("click").bind("click",function(e){
			$(this).attr({"target":'_blank'});
		});
		
		$("#sotypelist li").die("click").live("click",function(e){
			var index=$(this).attr('_index');
			so.setSoType(index);
		});
		
	},
	loadData:function(index){
		var d=this.d;
		var html='';
		var solist='';
		for(var key=0;key<d.length;key++){
			var list=d[key]['data'];
			if(index==key){
				current='current';
			}else{
				current='';
			}
			solist+='<li _soname="'+d[key]['name']+'" _index="'+key+'"  _title="'+list.name+'" class="'+current+'"><span class="soicon '+d[key]['name']+'"></span></li>';
		}
		$("#sotypelist").html(solist);
	},
	setSoType:function(index){
			if(index=='undefined' || index<0){return;}
			if(typeof this.d[index] == 'undefined'){
				index = 0;
			}
			var d=this.d[index];
			var list=d['data'];
			$("#soform").attr({'action':list.action});
			$("#keyword").attr({'name':list.keyname});
			$("#extparam").html(this.getparamInput(list.param));
			
			$("#sotypeico").removeAttr("class");
			$("#sotypeico").addClass("soicon "+d["name"]);
			$("#sotypeico").parent().attr({'href':list.homeurl})
			if(index!=T._searchIndex){
				$($("#sotypelist li").get(T._searchIndex)).removeClass('current');
				$($("#sotypelist li").get(index)).addClass('current');
				T._searchIndex=index;
				T.setParamdata();
			}
			
	},
	getparamInput:function(str){
		var html='';
		var arr=str.split(',');
		for(var i=0;i<arr.length; i++){
			var d=arr[i].split('=');
			html+='<input type="hidden" name="'+d[0]+'" value="'+d[1]+'">';
		}
		return html;
	},
	isVisible:function(is,t){
		if(t=='init'){
			if(is=='1'){
				$("#searchbox").show();
			}else{
				$("#searchbox").hide();
			}
		}else if(t=='set'){
			var topval=0;
			if(is=='1'){
				T._search_topoffset=0;
				T.position();
				$("#searchbox").css({top:topval,'opacity':0});
				$("#searchbox").show();
				$("#searchbox").stop(true,false).animate({
					'top':T._search_top,
					'opacity':1
				},500,function(){$("#searchbox").show();});
			}else{
				T._search_topoffset=40;
				$("#searchbox").stop(true,false).animate({
					'top':topval,
					'opacity':0
				},500,function(){$("#searchbox").hide();T.position();});
				
			}
		}
	},
	autocomplete:function(){
		if(T._searchTip_url != ""){
			$('#keyword').autocomplete(T._searchTip_url, {
				selectFirst: false,
				dataType: 'json', 
				max: 10,    //列表里的条目数
				minChars: 0,    //自动完成激活之前填入的最小字符
				width: 434,     //提示的宽度，溢出隐藏
				scrollHeight: 300,   //提示的高度，溢出显示滚动条
				matchContains: false,    //包含匹配，就是data参数里的数据，是否只要包含文本框里的数据就显示
				autoFill: false,    //自动填充
				formatItem: function(row, i,max) { 
					return row; 
				},
				parse: function(data) {
					var parsed = [];
					for(var i=0;i<data.length;i++){
						parsed.push({
						data: data[i],
						value: data[i],
						result: data[i]
						});
					}
					return parsed;
				}
			}).result(function(event, row, formatted) {
				//$($(this).parents('form')[0]).attr({"target":(T._opennewtab?'_blank':'_self')});
				$($(this).parents('form')[0]).attr({"target":'_blank'});
				$(this).parents('form')[0].submit();
			});
		}
	}
}
//设置*********************************************/
set = {
	init:function(){
		$(".setuppage").unbind("mouseup").bind("mouseup",function(){
				return false;
		});
		//////-----------------------------------
		this.setuppage();
		this.setopacity();
		this.setTabBG();
		this.setupbtn();
		this.btnDefault();
	},
	setupbtn:function(){
		$("#setupbtn").unbind("click").bind("click",function(){
			var isshow=$("#setuppage").is(":visible");
			if(!isshow){
				$("#setuppage").show();
			}else{
				$("#setuppage").hide();
			}
		});
	},
	btnDefault:function(){
		$("#defaultdata").unbind("click").bind("click",function(){
				dialog.init({Close:'hide',w:330,h:160,obj:'#confirm',html:Confirm.template()});
				Confirm.init(1,chrome.i18n.getMessage('sysHint'),chrome.i18n.getMessage('recoveryConfirm'),function(){
					update.def(1);
					dialog.showHide(false);
				},function(){dialog.showHide(false);});
				Confirm.bind();
		});
	},
	setuppage:function(){
		if(T._opennewtab=='1'){$(".searchbox >#opennew").attr({'checked':true});}
		if(T._issearchbox=='1'){$(".searchbox >#issearchbox").attr({'checked':true});}
		
		$(".searchbox input[type='checkbox']").unbind("click").bind("click",function(e){
			var id=$(this).attr('id');
			var val=$(this).attr('checked');
			if(id=='opennew'){
				T._opennewtab=val?1:0;
			}else if(id=='issearchbox'){
				T._issearchbox=val?1:0;
				so.isVisible(T._issearchbox,'set');
			}
			T.setParamdata();
		});
	},
	setopacity:function(){
		var slider=$.fn.jSlider({
				renderTo: '.sliderarea',
				defaultpos:T._boxtabopacity,
				size: { barWidth: 270, sliderWidth: 15 },
				 barCssName: 'sliderBG fl',
				 sliderCssName:'slider-thumb',
				onChanging: function(percentage, e) {
				  //console.log(percentage);
				   T._boxtabopacity=percentage;
				  $(T._dimensions+" li").css({'opacity':1-percentage});
				  T.setParamdata();
				}
			});
	},
	setTabBG:function(){
		var self=".bgimglist .imgbgbox";
		$(self).each(function(index, el) {
			if(index==T._bgIndex){
				$(el).addClass('checked');
			}else{
				$(el).removeClass('checked');
			}
		});
		$(self).unbind('click').bind("click",function(){
			T._bgIndex=$(this).attr('_index');
			$(this).siblings().removeClass('checked');
			$(this).addClass('checked');
			T._bglocalImg='';
			T.setParamdata();
			T.SetMainBG(T._bgIndex);
		});
		
		$("#J-selfSet-bg").unbind('change').bind('change',function(){
			/*var file=$(this).val();
			if(file!=''){
				T._bgIndex=-1;
				T._bglocalImg=file;
				T.setParamdata();
				T.SetMainBG(T._bgIndex);
			}*/
			
		});
	}
}
/////全局*********************************************/
T={
	_ftbox:'#ftbox',
	_boxlist:'#boxlist',
	_dimensions:".dimensions",
	_searchTip_url:"",
	_ftbox_bottom:5,
	_search_top:30,
	_search_topoffset:0,
	_windowHeight:0,
	_windowWidth:0,
	_Boxs_scale:0,
	_tabData:{},
	//-需要设置参数------
	_searchIndex:config.sotype,
	_bgIndex:0,
	_bglocalImg:'',
	_opennewtab:config.targetSwitch,
	_issearchbox:config.searchshow,
	_boxtabopacity:0,
	_mainBG:'',
	//-需要设置参数 END------
	initParam:function(){
		this._searchIndex=config.sotype;
		this._bgIndex=0;
		this._bglocalImg='';
		this._opennewtab=config.targetSwitch;
		this._issearchbox=config.searchshow;
		this._boxtabopacity=0;
		this._mainBG='';
	},
	init:function(){
		this.initParam();
		this.loadJson();
		this.delboxData();
		update.init();
		this.getParamdata();
		so.init();
		ftbox.init();
		boxs.init();
		this.position();
		menu.init();
		set.init();
		this.SetMainBG(T._bgIndex);
		
	},
	setParamdata:function(){
		storage.set(ParamName._searchIndex,this._searchIndex,false);
		storage.set(ParamName._bgIndex,this._bgIndex,false);
		storage.set(ParamName._bglocalImg,this._bglocalImg,false);
		storage.set(ParamName._opennewtab,this._opennewtab,false);
		storage.set(ParamName._issearchbox,this._issearchbox,false);
		storage.set(ParamName._boxtabopacity,this._boxtabopacity,false);
	},
	getParamdata:function(){
		var _searchIndex=storage.get(ParamName._searchIndex,false);
		if(_searchIndex!=null){
			this._searchIndex=_searchIndex;
			 storage.set(ParamName._searchIndex,this._searchIndex,false);
		}
		var _bgIndex=storage.get(ParamName._bgIndex,false);
		if(_bgIndex!=null){
			this._bgIndex=_bgIndex;
			 storage.set(ParamName._bgIndex,this._bgIndex,false);
		}
		var _bglocalImg=storage.get(ParamName._bglocalImg,false);
		if(_bglocalImg!=null){
			this._bglocalImg=_bglocalImg;
			 storage.set(ParamName._bglocalImg,this._bglocalImg,false);
		}
		
		var _opennewtab=storage.get(ParamName._opennewtab,false);
		if(_opennewtab!=null){
			this._opennewtab=_opennewtab;
			 storage.set(ParamName._opennewtab,this._opennewtab,false);
		}
		var _issearchbox=storage.get(ParamName._issearchbox,false);
		if(_issearchbox!=null){
			this._issearchbox=_issearchbox;
			 storage.set(ParamName._issearchbox,this._issearchbox,false);
		}
		var _boxtabopacity=storage.get(ParamName._boxtabopacity,false);
		if(_boxtabopacity!=null){
			this._boxtabopacity=_boxtabopacity;
			 storage.set(ParamName._boxtabopacity,this._boxtabopacity,false);
		}
		
		
		this._search_topoffset=this._issearchbox!='1'?40:0;
	},
	loadJson:function(){
		var d=storage.get(ParamName._LocalData,true);
		if(d==null){
			d=_tabData;
			this.setTabDataJson(d);
		}
		this._tabData=d;
	},
	refreshHtml:function(){
		boxs.loadboxlist();
		ftbox.loadftbox();
		menu.init();
		this.position();
	},
	setTabDataJson:function(d){
		storage.set(ParamName._LocalData,d,true);
		this._tabData=d;
	},
	getPageid:function(){//获取默认显示页
		var d=storage.get(ParamName._defaultPageID,false);
		return d==null?-1:d;
	},
	delboxData:function(){
		var del=config.delwebid;
		if(del.length<=0){return;}
		
		var d=T._tabData;
		for(var j=0;j<d.length;j++){
			var data=d[j]['data'];
			for(var ji=0;ji<data.length;ji++){
				var dji=data[ji]['id'];
				for(var i=0;i<del.length;i++){
					if(dji==del[i]){
						d[j]['data'][ji]=[];	
					}
				}
			}
		}
		T.setTabDataJson(d);
	},
	setPageid:function(pageid){
		pageid = pageid=='undefined'?-1:pageid;
		storage.set(ParamName._defaultPageID,pageid,false);
	},
	position:function(){
		this._windowHeight=$(window).height();
		this._windowWidth=$(window).width();
		
		var ftbox_left=(this._windowWidth-ftbox._width)/2;
		$(this._ftbox).css({left:ftbox_left,bottom:this._ftbox_bottom/100*this._windowHeight});
		
		$(this._dimensions).each(function(i, n) {
			var bleft=parseInt($(n).css('left'));
			bleft=bleft>0?T._windowWidth:(bleft<0?-T._windowWidth:0);
			$(n).css({"left":bleft+"px","width":T._windowWidth+"px","height":T._windowHeight+"px"});
			
		});
		
		
		
		//---------------
		var temW=parseInt($(this._dimensions+" .space").css('width'));
		var temH=parseInt($(this._dimensions+" .space").css('height'));
		var boxs_spaceL=(this._windowWidth-temW)/2;
		var boxs_spaceT=(this._windowHeight-temH)/2-T._search_topoffset;
		this._Boxs_scale=(this._windowHeight-(0.2 * parseInt(this._windowHeight))-T._search_top-60+T._search_topoffset)/(temH)
		$(this._dimensions+" .space").css({top:boxs_spaceT,left:boxs_spaceL,'-webkit-transform':'scale('+this._Boxs_scale+')','-moz-transform':'scale('+this._Boxs_scale+')'});
		
		$("#searchbox").css({"top":this._windowHeight*0.08});
	},
	truncate:function (str,lng) {
		if (str) {
			if (str.len > lng) {
				return str.sub(lng);// + '...'
			} else {
				return str.sub(lng);
			}
		}
		return ''
	},
	SetMainBG:function(index){
		if(index==-1){
			if(T._bglocalImg!=''){
				$("body").attr({'style':"background-color: rgb("+T._bglocalImg+"); zoom: 1; background-position: initial initial; background-repeat: initial initial;"});		
			}
		}else{
			var self=".bgimglist .imgbgbox";
			var obj=$(self).get(index);
			var _type=$(obj).attr('_type');
			var bgdata=$(obj).attr('bg-data');
			if(_type=='color'){
				$("body").attr({'style':"background-color: rgb("+bgdata+"); zoom: 1; background-position: initial initial; background-repeat: initial initial;"});	
			}else{
				$("body").attr({'style':"background-image: url("+bgdata+"); background-size: cover, 100%; zoom: 1; background-position: 50% 50%; background-repeat: initial initial;"});
			}
		}
	}
};
	
update = {
	uptime:0,
	init: function(){
		this.getuptime();
		if(this.uptime < json_update.uptime && json_update.isupdate == 1){
			this.UpLoadData();
		}
	},
	getuptime:function(){
		var d = storage.get("uptime",true);
		if(d == null){
			d = json_update.uptime;
			this.setuptime(d);
		}
		this.uptime = d;
	},
	setuptime:function(d){
		storage.set("uptime",d,true);
		this.uptime = d;
	},
	UpLoadData:function(){
		//更新用户连接
		//update.setuptime(json_update.uptime);
		//T.setTabDataJson(data);
		//T.init();
	},
	def:function(alls){
		storage.remove(ParamName._defaultPageID);
		storage.remove(ParamName._boxtabopacity);
		storage.remove(ParamName._opennewtab);
		storage.remove(ParamName._searchIndex);
		storage.remove(ParamName._issearchbox);
		
		if(alls==1){
			storage.remove(ParamName._bgIndex);
			storage.remove(ParamName._bglocalImg);
			storage.remove(ParamName._userAddLastTabID);
			storage.remove(ParamName.uptime);
			T.setTabDataJson(_tabData);
			T.init();
		}
	}
}
String.prototype.len=function(){
	return this.replace('/[^\0xa1-\0xff]/g',"**").length; 
	}
String.prototype.sub = function(n){ 
	var r = '/[^\x00-\xff]/g'; 
	if(this.replace(r, "**").length <= n) 
		return this;// 
	//n = n - 3; 
	var m = Math.floor(n/2); 
	for(var i=m; i<this.length; i++) {
		 if(this.substr(0, i).replace(r, "**").length>=n) {
			  return this.substr(0, i); 
		} 
	} 
	return this;
};

Array.prototype.remove=function(dx){
	if(isNaN(dx)||dx>this.length){
		return false;
	}
	for(var i=0,n=0;i<this.length;i++){
		if(this[i]!=this[dx]){
			this[n++]=this[i]
		}
	}
	this.length-=1
}
function filterParam(url) {
	return (url||'').replace(/\?.*$/ig, '');
}
function isContains(child, parent) {
    while (child && child != parent) {
        child = child.parentNode
    }
    return (child == parent)
}
function isContainsClass(child, parentClass) {
    while (child && !$(child).hasClass(parentClass)) {
        child = child.parentNode
    }
    return ($(child).hasClass(parentClass))
}
function isHttp(str) {
	str = str + '';
	return !isEmpty(str) && (str.substr(0, 7).toLowerCase() == 'http://' ||  str.substr(0, 8).toLowerCase() == 'https://');
}
function  isEmpty(str) {
	return (str + '').length <= 0
}
	
//语言包
function getI18nMsg (msgname) {
	try {
		return chrome.i18n.getMessage(msgname);
	} catch(err) {
		return msgname;
	}			
};
function initChromeI18n(obj) {
	var _data,key,_mKey;
	var arr	= ['content','value','title','placeholder'];
	for(var i = 0, l = arr.length; i < l; i++){
		_mKey	= arr[i];
		key	= 'data-i18n-'+_mKey+'';
		if(typeof obj != 'undefined'){
			_data	= obj.find('['+key+']');
		}else{
			_data	= $('['+key+']');
		}
		if(_data.length > 0){
			for(var n = 0; n < _data.length; n++){
				var message = getI18nMsg(_data[n].getAttribute(key));
				if (message) {
					switch(_mKey){ 
						case 'content':
							$(_data[n]).html(message);
							break;
						case 'value':
							$(_data[n]).val(message);
							break;
						default:
							$(_data[n]).attr(_mKey, message);
					}
				}
			}
		}
	}
};

//create,update tab
function openTab(targetSwitch,url,tabID){
	tabID = parseInt(tabID);
	try{
		if(targetSwitch == '0'){
			chrome.tabs.update(
				tabID,
				{
					url: url
				}
			);
		}else{
			chrome.tabs.create(
				{
					url: url,
					index: tabID + 1,
				}
			);
		}
	}catch(e){
		if(targetSwitch == '0'){
			if (window.top != window.self) {
				window.top.location.href = url;
			}else{
				window.location.href = url;
			}
		}else{
			window.open(url);
		}
	}
}